<?php
namespace App\Think\SdkGame;

class IG{

    // 请求URL
    // 官方彩登录：http://gfcswapi.iasia99.com/gfcapisw/app/api.do
    // 官方彩报表拉取:http://gfcswapi.iasia99.com/gfcapirecordsw/app/api.do
    // 
    // 香港彩登录：http://lottosw.iasia99.com/igapiyflottosw/app/api.do
    // 传统彩登录：http://tradesw.iasia99.com/igapiyftradesw/app/api.do
    // 
    // 存取款：http://tradesw.iasia99.com/igapiyftradesw/app/api.do
    // 报表拉取：http://igyfsw.iasia99.com/igapiyfrecordsw/app/api.do
    
    // 测试后台地址：http://igyfswag.iasia99.com
    // 账户：BT          密码：qqww112288
    // hashCode：BT_bdbedffd-2288-4a2b-9058-0a60bb049
    
    /**
     * 初始化
     * @param string $type 彩种类型|GFC=官方彩，LOTTO=香港彩，LOTTERY=时时彩
     */
    public function __construct($type = 'LOTTERY')
    {
        $this->hashCode = 'BT_bdbedffd-2288-4a2b-9058-0a60bb049';
        $this->type = $type;
        $param = $this->init_param($type);
        $this->login_url = $param['login_url'];
        $this->trans_url = $param['trans_url'];
        $this->pull_url  = $param['pull_url'];
        $this->plat_type = $param['plat_type'];
    }

    public function init_param($type='LOTTERY'){
        $plat_type = 'IG';
        // 官方彩 api
        if($type == 'GFC'){
            $login_url = 'http://gfcswapi.iasia99.com/gfcapisw/app/api.do';
            $trans_url = 'http://tradesw.iasia99.com/igapiyftradesw/app/api.do';
            $pull_url  = 'http://gfcswapi.iasia99.com/gfcapirecordsw/app/api.do';
        }
        // 香港彩 api
        if($type == 'LOTTO'){
            $login_url = 'http://lottosw.iasia99.com/igapiyflottosw/app/api.do';
            $trans_url = 'http://tradesw.iasia99.com/igapiyftradesw/app/api.do';
            $pull_url  = 'http://igyfsw.iasia99.com/igapiyfrecordsw/app/api.do';
        }
        // 时时彩 api
        if($type == 'LOTTERY'){
            $login_url = 'http://lotterysw.iasia99.com/igapiyflotterysw/app/api.do';
            $trans_url = 'http://tradesw.iasia99.com/igapiyftradesw/app/api.do';
            $pull_url  = 'http://igyfsw.iasia99.com/igapiyfrecordsw/app/api.do';
        }
        return ['login_url'=>$login_url, 'trans_url'=>$trans_url, 'pull_url'=>$pull_url, 'plat_type'=>$plat_type];
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            'username' => $param['account'],
            'nickname' => $param['account'],
            'password' => md5($param['account']),
            'currency' => 'TEST',
            'language' => 'CN',
            'line'     => 1,
            //GFC=官方彩，LOTTO=香港彩，LOTTERY=时时彩
            'gameType' => $this->type,
            
            'gfcTray'     => 'A',
            'lotteryTray' => 'A',
            'lottoTray'   => 'A',

            'gfcPag'      => '',
            'homeUrl'     => '',
            'lc'          => 'y'
        );
        $command = 'LOGIN';
        $url = $this->build_request($command, $req_data);
        $res = $this->sendRequest($this->login_url, $url);
        return ['code'=>$res['code'], 'url'=>$res['params']['link'] ];
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        return $this->register($param);
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            "username" => $param['account'],
            "password" => md5($param['account'])
        );
        $command = 'GET_BALANCE';
        $url = $this->build_request($command, $req_data);
        $res = $this->sendRequest($this->trans_url, $url);
        // return $res;//['code'=>$res['code'], 'balance'=>(float)$res['totalScore'] ];
        return ['code'=>$res['code'], 'balance'=>(float)$res['params']['balance'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            "username" => $param['account'],
            "password" => md5($param['account']),
            'ref'      => $param['orderid'],
            "amount"   => (string)$param['money'],
            'desc'     => ''
        );
        $command = 'DEPOSIT';
        $url = $this->build_request($command, $req_data);
        $res = $this->sendRequest($this->trans_url, $url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            "username" => $param['account'],
            "password" => md5($param['account']),
            'ref'      => $param['orderid'],
            "amount"   => (string)$param['money'],
            'desc'     => ''
        );
        $command = 'WITHDRAW';
        $url = $this->build_request($command, $req_data);
        $res = $this->sendRequest($this->trans_url, $url);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    public function transOutInfo($param){
        $req_data = array(
            "username" => $param['account'],
            "password" => md5($param['account'])
        );
        $command = 'GET_BALANCE';
        $url = $this->build_request($command, $req_data);
        $res = $this->sendRequest($this->trans_url, $url);
        return $res;
    }

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        //官方彩
        $param['type'] = 'GFC';
        $res = \think\Db::name('raw_data')->where("plat_type='{$this->plat_type}' AND plat_ext='{$param['type']}'")->order("updatetime DESC")->value('data_json');
        $data_json = json_decode($res, true);
        $param['bet_id'] = isset($data_json['sequenceNo']) ? $data_json['sequenceNo'] : "0";
        $res_gfc = $this->gameLogSyncHandle($param);
        //传统彩
        $param['type'] = 'LOTTERY';
        $res = \think\Db::name('raw_data')->where("plat_type='{$this->plat_type}' AND plat_ext='{$param['type']}'")->order("updatetime DESC")->value('data_json');
        $data_json = json_decode($res, true);
        $param['bet_id'] = isset($data_json['sequenceNo']) ? $data_json['sequenceNo'] : "0";
        $res_ctc = $this->gameLogSyncHandle($param);

        $tmp_list     = array_merge((array)$res_gfc['list'], (array)$res_ctc['list']);
        $tmp_raw_data = array_merge((array)$res_gfc['raw_data'], (array)$res_ctc['raw_data']);
        if( $res_gfc['code']>0 && count($tmp_list) > 0){
            return ['code'=>$res_gfc['code'], 'list'=>$tmp_list, 'raw_data'=>$tmp_raw_data];
        }
        return ['code'=>-1, 'list'=>$tmp_list, 'raw_data'=>$tmp_raw_data];
        
    }

    //游戏注单同步处理
    private function gameLogSyncHandle($param){
        $req_data = array(
            "beginId" => @is_string($param['bet_id']) ? $param['bet_id'] : (string) "0",
            "count"   => "1000"
        );
        //区分彩种
        $color_type = (string)$param['type'];
        if($color_type == 'GFC')     $command = 'GET_GFC_RECORD_BY_SEQUENCENO';
        if($color_type == 'LOTTERY') $command = 'GET_LOTTERY_RECORD_BY_SEQUENCENO';
        if($color_type == 'LOTTO')   $command = 'GET_LOTTO_RECORD_BY_SEQUENCENO';

        //拉取注单
        $init = $this->init_param($color_type);
        $url = $this->build_request((string)$command, $req_data);
        $res = $this->sendRequest($init['pull_url'], $url);
        //数据返回处理
        $list = @$res['params']['recordList'];
        $rs = $raw_data = [];
        //香港彩/时时彩
        if( ($color_type == 'LOTTO' || $color_type == 'LOTTERY') && is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                $status = $v['resultTime']>0 ? 1 : 0;
                //流水
                if($v['winLoss'] < 0)  $money_valid = -$v['winLoss'];
                if($v['winLoss'] >= 0) $money_valid = $v['winLoss']<$v['stakeAmount'] ? $v['winLoss'] : $v['stakeAmount'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'plat_ext'      => $color_type,
                    'game_type'     => $v['gameInfoId'],
                    'game_name'     => @$this->game_name($v['gameInfoId'], $color_type),
                    'game_user'     => $v['username'],
                    'bet_id'        => $v['betId'],
                    'money_bet'     => $v['stakeAmount'],
                    'money_valid'   => $money_valid,//$v['validStake'],
                    'money_winlose' => $v['winLoss'],
                    'money_fee'     => $v['commAmount'],
                    'createtime'    => (int)($v['betTime']/1000),
                    'updatetime'    => (int)($v['resultTime']/1000),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['plat_ext']  = $color_type;
                $raw_data[$k]['bet_id']    = $v['betId'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = (int)($v['resultTime']/1000);
            }
        }

        //官方彩
        if( ($param['type'] == 'GFC') && is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                $status = $v['resultTime']>0 ? 1 : 0;
                //流水
                if($v['winLoss'] < 0)  $money_valid = -$v['winLoss'];
                if($v['winLoss'] >= 0) $money_valid = $v['winLoss']<$v['stakeAmount'] ? $v['winLoss'] : $v['stakeAmount'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'plat_ext'      => $color_type,
                    'game_type'     => $v['gameInfoId'],
                    'game_name'     => @$this->game_name($v['gameInfoId']),
                    'game_user'     => $v['username'],
                    'bet_id'        => $v['betId'],
                    'money_bet'     => $v['stakeAmount'],
                    'money_valid'   => $money_valid,//$v['validStake'],
                    'money_winlose' => $v['winLoss'],
                    'createtime'    => (int)($v['betTime']/1000),
                    'updatetime'    => (int)($v['resultTime']/1000),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['plat_ext']  = $color_type;
                $raw_data[$k]['bet_id']    = $v['betId'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = (int)($v['resultTime']/1000);
            }
        }

        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == 0 ? 1 : $res['code'];
        return $res;
    }

    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url,$post_data=array(), $req_type=1){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 
            $jsonStr = json_encode($post_data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($jsonStr)
                )
            );
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        // echo $url;
        // print_r($jsonStr);
        // print_r($contents);
        $contents = json_decode($contents, true);

        //业务处理
        $res = $contents;
        if(!isset($res['errorCode']) || $res['errorCode'] != 0){
            $res['code'] = -1;
        }else{
            $res['code'] = 1;
        }
        return $res;
    }
    private function build_request($command='', array $param){
        $res = array('hashCode'=>$this->hashCode,'command'=>$command, 'params'=>$param);
        return $res;
    }

    //游戏列表
    public function game_list($type='LOTTERY'){
        if($type == 'LOTTERY' || $type == 'LOTTO'){
            $list = [
                '1'=>'广东快乐十分',
                '2'=>'重庆时时彩',
                '3'=>'北京赛车(PK10)',
                '4'=>'江苏骰宝(快3)',
                '5'=>'幸运农场',
                '6'=>'天津时时彩',
                '7'=>'新疆时时彩',
                '8'=>'江西时时彩',
                '9'=>'云南时时彩',
                '10'=>'上海时时彩',
                '11'=>'天津快乐十分',
                '12'=>'广西快乐十分',
                '13'=>'湖南快乐十分',
                '14'=>'安徽快3',
                '15'=>'广西快3',
                '16'=>'吉林快3',
                '17'=>'幸运飞艇',
                '18'=>'广东11选5',
                '19'=>'江西11选5',
                '20'=>'山东11选5',
                '21'=>'北京11选5',
                '22'=>'上海11选5',
                '23'=>'辽宁11选5',
                '24'=>'湖北11选5',
                '25'=>'江苏11选5',
                '26'=>'安徽11选5',
                '27'=>'北京快乐8',
                '28'=>'澳洲快乐8',
                '29'=>'韩国快乐8',
                '30'=>'加拿大卑斯快乐8',
                '31'=>'加拿大西部快乐8',
                '32'=>'斯洛伐克快乐8',
                '33'=>'马耳他快乐8',
                '34'=>'台湾宾果',
                '35'=>'东京快乐8',
                '36'=>'福彩3D',
                '37'=>'排列三',
                '38'=>'云南快乐十分',
                '39'=>'北京快8PC蛋蛋',
                '40'=>'澳洲快8PC蛋蛋',
                '41'=>'韩国快8PC蛋蛋',
                '42'=>'加拿大快8PC蛋蛋',
                '43'=>'加拿大大西部快8PC蛋蛋',
                '44'=>'斯洛伐克PC蛋蛋',
                '45'=>'马耳他PC蛋蛋',
                '46'=>'台湾宾果PC蛋蛋',
                '47'=>'东京快乐8PC蛋蛋',
                '48'=>'极速赛车',
                '49'=>'极速时时彩',
                '50'=>'一分赛车',
                '51'=>'一分时时彩',
                '52'=>'极速快乐十分',
                '53'=>'极速十一选五',
                '54'=>'极速快三',
                '55'=>'极速快乐8',
                '56'=>'极速3D',
                '57'=>'极速PC蛋蛋',
                '58'=>'极速六合彩',
                '59'=>'北京快3',
                '60'=>'上海快3',
                '61'=>'湖北快3',
                '62'=>'河北快3',
                '63'=>'甘肃快3',
                '64'=>'江西快3',
                '65'=>'三分赛车',
                '66'=>'三分时时彩',
                '67'=>'三分快乐十分',
                '68'=>'三分快3',
                '69'=>'三分十一选五',
                '70'=>'三分3D',
                '71'=>'三分快乐8',
                '72'=>'三分PC蛋蛋',
                '73'=>'IG赛车',
                '74'=>'IG时时彩',
                '75'=>'IG六合',
                '76'=>'十分六合',
                '77'=>'IG飞艇',
                '78'=>'河内一分彩',
                '79'=>'河内五分彩',
            ];
        }
        if($type == 'GFC'){
            $list = [
                '1'=>'北京赛车',
                '2'=>'幸运飞艇',
                '3'=>'极速赛车',
                '4'=>'一分赛车',
                '5'=>'三分赛车',
                '6'=>'IG赛车',
                '7'=>'IG飞艇',
                '21'=>'江苏快3',
                '22'=>'安徽快3',
                '23'=>'广西快3',
                '24'=>'吉林快3',
                '25'=>'极速快3',
                '26'=>'北京快3',
                '27'=>'上海快3',
                '28'=>'湖北快3',
                '29'=>'河北快3',
                '30'=>'甘肃快3',
                '31'=>'江西快3',
                '32'=>'三分快三',
                '41'=>'重庆时时彩',
                '42'=>'天津时时彩',
                '43'=>'新疆时时彩',
                '44'=>'江西时时彩',
                '45'=>'云南时时彩',
                '46'=>'极速时时彩',
                '47'=>'一分时时彩',
                '48'=>'排列五',
                '49'=>'三分时时彩',
                '50'=>'IG时时彩',
                '51'=>'河内一分彩',
                '52'=>'河内五分彩',
                '61'=>'广东11选5',
                '62'=>'江西11选5',
                '63'=>'山东11选5',
                '64'=>'北京11选5',
                '65'=>'上海11选5',
                '66'=>'辽宁11选5',
                '67'=>'湖北11选5',
                '68'=>'江苏11选5',
                '69'=>'安徽11选5',
                '70'=>'极速11选5',
                '71'=>'三分11选5',
                '81'=>'福彩3D',
                '82'=>'极速3D',
                '83'=>'三分3D',
            ];
        }
        return $list;
    }
    //游戏名称
    public function game_name($gameid, $type='GFC'){
        $pre = '';
        if($type == 'GFC')     $pre = '官方版|';
        if($type == 'LOTTO')   $pre = '香港版|';
        if($type == 'LOTTERY') $pre = '传统版|';
        $list = $this->game_list($type);
        return isset($list[$gameid]) ? $list[$gameid] : '未知游戏';
    }

}


